import { useState, useRef, useMemo } from 'react';
import { message, Popconfirm, Tag, Tabs } from 'antd';
import { QueryTable } from '@/components/QueryTable';
import OperateCustomerDrawer from './operateCustomerDrawer';
import BusinessActionDrawer from '../businessManage/businessActionDrawer';
import useCustomerFellowLog from '@/components/_hooks/useCustomerFellowLog';
import useCustomerChange from '@/components/_hooks/useCustomerChange';
import { customerTypeTagMapping } from '@/utils';
import { deleteCustomer, transferCustomer } from '@/api';
import { statusArr, customRankArr, notFellowMapping, activeKeyProps } from './metaData';

import './index.less';

export default function Customer(props) {
  const { customerType } = props;

  const [showModal, setModal] = useState(false);
  const [businessActionDrawer, setBusinessActionDrawer] = useState(false);
  const [editItem, setEditItem] = useState({});
  const tableRef = useRef();
  const [setFellowDrawerStatus, fellowDrawer] = useCustomerFellowLog();
  const onFinish = (data?: any) => {
    tableRef?.current?.refreshTable();
  };
  const [openTransDrawer, customerChangeDrawer] = useCustomerChange({
    callback: onFinish,
  });

  const onDrawershow = (id: any, showStatus: boolean) => {
    setModal(showStatus);
  };

  const delCustomer = (id) => {
    deleteCustomer({ id })
      .then((data) => {
        if (!data) return;
        message.success('删除成功');
        onFinish?.();
      })
      .catch((err) => {
        throw err;
      });
  };

  const transCustomer = (customerId) => {
    transferCustomer({ customerId, followUpUserId: null })
      .then((data) => {
        if (!data) return;
        message.success('操作成功');
        tableRef?.current?.refreshTable();
      })
      .catch((err) => {
        throw err;
      });
  };

  const columns = [
    {
      dataIndex: 'customerId',
      key: 'customerId',
      title: '客户ID',
    },
    {
      dataIndex: 'customerName',
      key: 'customerName',
      title: '客户姓名',
      width: 100,
      ellipsis: true,
      searchConfig: {
        type: 'input',
      },
      render: (text, record) => {
        return (
          <a onClick={() => setFellowDrawerStatus(true, record?.customerId)}>
            {text}
          </a>
        );
      },
    },
    {
      dataIndex: 'loanLimit',
      key: 'loanLimit',
      title: '贷款额度',
    },
    {
      dataIndex: 'status',
      key: 'status',
      title: '客户状态',
      searchConfig: {
        type: 'select',
        selectConfig: {
          data: statusArr,
          optionValue: 'value',
          optionLabel: 'name',
        },
      },
      render: (_, record) => {
        const statusObj = customerTypeTagMapping[record?.status] ?? {};
        return <Tag color={statusObj?.color}>{statusObj?.content}</Tag>;
      },
    },
    {
      dataIndex: 'customerAddress',
      key: 'customerAddress',
      title: '地址',
      ellipsis: true,
    },
    {
      dataIndex: 'phone',
      key: 'phone',
      title: '客户电话',
      width: 130,
      searchConfig: {
        type: 'input',
      },
    },
    {
      dataIndex: 'weChat',
      key: 'weChat',
      title: '微信',
    },
    {
      dataIndex: 'gender',
      key: 'gender',
      title: '客户性别',
      enumMapping: {
        man: '男',
        woman: '女',
      },
    },
    {
      dataIndex: 'age',
      key: 'age',
      title: '客户年龄',
    },
    {
      dataIndex: 'customerRank',
      key: 'customerRank',
      title: '客户星级',
      searchConfig: {
        type: 'select',
        selectConfig: {
          data: customRankArr,
          optionValue: 'value',
          optionLabel: 'name',
        },
      },
      render: (text: number) => {
        const contentText = customRankArr?.find((i) => i.value == text)?.name;
        return contentText ? <Tag color='gold'>{contentText}</Tag> : '--';
      },
    },
    {
      dataIndex: 'identityNumber',
      key: 'identityNumber',
      title: '身份证号码',
      ellipsis: true,
    },
    {
      dataIndex: 'action',
      key: 'action',
      title: '操作',
      fixed: 'right',
      // actionGroup: [
      //   {
      //     title: '编辑',
      //     onClick: (_, record) => {
      //       setModal(true)
      //       setEditItem(record)
      //     }
      //   },
      //   {
      //     title: '新增邀约',
      //     onClick: (_, record) => {
      //       setBusinessActionDrawer(true)
      //       setEditItem(record)
      //     }
      //   }
      // ],
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                setModal(true);
                setEditItem(record);
              }}
            >
              编辑
            </a>
            <br />
            <a
              onClick={() => {
                setBusinessActionDrawer(true);
                setEditItem(record);
              }}
            >
              新增邀约
            </a>
            <br />
            <a onClick={() => openTransDrawer(record)}>转派</a>
            <br />
            <Popconfirm
              title='放入公海'
              description='确认将该客户放入公海吗?'
              onConfirm={() => transCustomer(record?.customerId)}
              okText='确定'
              cancelText='取消'
            >
              <a>放入公海</a>
            </Popconfirm>
            <br />
            <Popconfirm
              title='客户删除'
              description='确认删除此客户吗?'
              onConfirm={() => delCustomer(record?.customerId)}
              okText='确定'
              cancelText='取消'
            >
              <a>删除</a>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  if (customerType === 'all') {
    columns.splice(6, 0, 
      {
        dataIndex: 'followUpUserName',
        key: 'followUpUserName',
        title: '负责人',
      })
  }

  const [activeKey, setActiveKey] = useState<activeKeyProps>('all')

  const tableContent = useMemo(() => {
    const info = notFellowMapping[activeKey]
    return (
      <div className='feedback-container'>
        <QueryTable
          reqExtraParams={{ queryType: customerType === 'all' ? 'ALL' : 'MY_FOLLOW_UP', ...info }}
          ref={tableRef}
          columns={columns}
          pagingInServer
          requestUrl='/crm/customer/page'
          responseDatafield='data'
          multipleButtons={[
            {
              type: 'primary',
              disabled: false,
              clickFn: () => setModal(true),
              text: '新增',
            },
          ]}
        />
      </div>
    );
  }, [activeKey])

  const items = [
    {
      key: 'all',
      label: '全部',
      children: activeKey === 'all' && tableContent,
    },
    {
      key: 'three',
      label: '3天内跟进',
      children: activeKey === 'three' && tableContent,
    },
    {
      key: 'three2seven',
      label: '3-7天未跟进',
      children: activeKey === 'three2seven' && tableContent,
    },
    {
      key: 'seven',
      label: '7天未跟进',
      children: activeKey === 'seven' && tableContent,
    },
  ]
  return (
    <>
      <Tabs
        defaultActiveKey="all"
        items={items}
        onChange={(key) => {
          setActiveKey(key as activeKeyProps)
          // tableRef?.current?.refreshTable();
        }} />
      <OperateCustomerDrawer
        pageType='myCustomer'
        setEditItem={setEditItem}
        editItem={editItem}
        isShow={showModal}
        onFinish={onFinish}
        onCancel={onDrawershow}
      />
      <BusinessActionDrawer
        businessType='invation'
        setEditItem={setEditItem}
        editItem={editItem}
        isShow={businessActionDrawer}
        onFinish={onFinish}
        onCancel={setBusinessActionDrawer}
      />
      {fellowDrawer}
      {customerChangeDrawer}
    </>
  )
}

Customer.route = {
  [MENU_PATH]: '/customer',
};
